const { fork } = require('child_process')
const fs =require('fs')
const Config = {
    port: 'COM3',
    port_speed:115200,
    board:'ESP8266'
}

const distDir = './dist';
const distFile = `${distDir}/index.js`

const isProd = process.env.NODE_ENV ==='prod'


function espruino_console(cb) {
    const buildproc = fork(
        require.resolve("espruino/bin/espruino-cli"),
        ["--board", Config.board, "-b", Config.port_speed, "--port", Config.port, "-w", 'index.js'],
        { cwd: distDir });
    buildproc.on('close', () => {
        cb();
    });
}

function prepare_for_espruino(cb) {
    if (!fs.existsSync(distFile)) {
        cb("main app file does not exit " + distFile);
        return;
    }
    const buildproc = fork(
        require.resolve("espruino/bin/espruino-cli"),
        ["--board", Config.board, "-o", "index.js"],
        { cwd: distDir });
    buildproc.on('close', () => {
        cb('write-end');
    });
}

function espruinoPlugin() {
    return {
        name: "rollup-espruino-flash",
        writeBundle() {
            if(!isProd){
                espruino_console(function (){
                    console.log('connect-close')
                    process.exit(0)
                })
            }else {
                prepare_for_espruino(function (msg){
                    console.log(msg);
                })
            }
        }
    }
}


module.exports = {
    input: './src/index.js',
    output: {
        file: distFile,
        format: 'cjs'
    },
    plugins: [espruinoPlugin()]
}